package com.bestv.search.management.command;

import com.bestv.search.common.cache.SystemCache;
import com.bestv.search.common.dataSource.DataSourceKey;
import com.bestv.search.common.model.PersonExtend;
import com.bestv.search.common.model.PersonProduct;
import com.bestv.search.common.model.SysUser;
import com.bestv.search.common.service.PersonManager;
import com.bestv.search.common.util.StringConst;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

public class PersonCommand {

    protected final Log log = LogFactory.getLog(getClass());
    private PersonManager personManager;
    private SystemCache systemCache;

    public String uploadAvatar(SysUser user, HttpServletRequest request, DataSourceKey dsKey) {
        String personId = request.getParameter("personId");
        if (personId == null) {
            log.error("Person id can't be null");
            return "{success:false}";
        }

        try {
            @SuppressWarnings("unchecked")
            List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
            for (FileItem item : items) {
                if ("avatarFilePath".equals(item.getFieldName())) {
                    byte[] avatar = item.get();
                    if (avatar == null) {
                        log.error("Person av can't avatar null");
                        return "{success:false}";
                    } else {
                        personManager.updateAvatar(dsKey, personId, avatar);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "{success:true}";
    }

    public String getPersonByName(SysUser user, HttpServletRequest request, DataSourceKey dsKey) {
        String keyword = request.getParameter("keyword");
        String start = request.getParameter("start");
        String limit = request.getParameter("limit");
        String nationality = request.getParameter("nationality");

        // Keyword
        if (keyword == null || keyword.equals(StringConst.EMPTY)) {
            log.error("Please provide keyword");
            return "{'totalCount':0,'results':[error]}";
        }

        // Start
        int startInt = 0;
        try {
            startInt = Integer.parseInt(start);
        } catch (Exception e) {
            log.warn("Parse start node to integer error!");
            startInt = 0;
        }

        // Limit
        int limitInt = 0;
        try {
            limitInt = Integer.parseInt(limit);
        } catch (Exception e) {
            log.warn("Parse start node to integer error!");
            limitInt = 20;
        }

        String[] nationalityArray = null;
        if (nationality == null || nationality.equals(StringConst.EMPTY) || nationality.startsWith("全部")) {
            nationalityArray = null;
        } else {
            nationalityArray = nationality.split(StringConst.SPACE);
        }

        // get data
        List<PersonExtend> list = personManager.getPersonByName(dsKey, keyword, nationalityArray, startInt, limitInt);

        int total = 0;
        if (list != null && list.size() > 0) {
            total = personManager.getPersonCountByName(dsKey, keyword, nationalityArray);
        }

        String url = systemCache.getWebServiceEngineUrls().get(dsKey.toString());
        String[] soapUrls = StringUtils.tokenizeToStringArray(url, SystemCache.WEB_SERVICE_EURL_DELIMITERS);

        if (soapUrls == null || soapUrls.length == 0) {
            log.error("Gets info failed, no web service interface found from site " + dsKey.toString());
            return "{'totalCount':0,'results':[error]}";
        } else {
            String avatarRoot = soapUrls[0].replace("/SearchService.ws", "/avatar/");

            // build to json string
            JSONArray array = new JSONArray();
            if (list != null) {
                for (PersonExtend person : list) {
                    JSONObject obj = new JSONObject();
                    String avatarName = null;
                    if (person.getAvatar() != null) {
                        avatarName = person.getPersonId() + StringConst.UNDERLINE + 0 + StringConst.JPGSUFFIX;
                    } else if (person.getAvatar_iqiyi() != null) {
                        avatarName = person.getPersonId() + StringConst.UNDERLINE + 1 + StringConst.JPGSUFFIX;
                    } else if (person.getAvatar_youku() != null) {
                        avatarName = person.getPersonId() + StringConst.UNDERLINE + 2 + StringConst.JPGSUFFIX;
                    } else {
                        avatarName = "default.jpg";
                    }

                    try {
                        obj.put("name", person.getName());
                        obj.put("avatar", avatarRoot + avatarName);

                        obj.put("code", person.getPersonId());
                    } catch (JSONException e) {
                        log.error("Convert to JSON Object failed");
                        log.error(e);
                        e.printStackTrace();
                        return "{'totalCount':0,'results':[error]}";
                    }

                    array.put(obj);
                }

                return "{'totalCount':" + total + ",'results':" + array.toString() + "}";
            }
        }

        return "{'totalCount':0,'results':[error]}";
    }

    public String getPersonDetail(SysUser user, HttpServletRequest request, DataSourceKey dsKey) {
        String personId = request.getParameter("personId");
        if (personId == null) {
            log.error("Person id can't be null");
            return "{success:false}";
        }

        PersonExtend person = personManager.getPersonById(dsKey, personId);

        // Convert to json object
        JSONObject personJson = new JSONObject();
        try {
            personJson.put("name", person.getName());

            String url = systemCache.getWebServiceEngineUrls().get(dsKey.toString());
            String[] soapUrls = StringUtils.tokenizeToStringArray(url, SystemCache.WEB_SERVICE_EURL_DELIMITERS);
            String avatarRoot = null;
            if (soapUrls != null && soapUrls.length != 0) {
                avatarRoot = soapUrls[0].replace("/SearchService.ws", "/avatar/");
            }
            String avatarName = null;
            if (person.getAvatar() != null) {
                avatarName = person.getPersonId() + StringConst.UNDERLINE + 0 + StringConst.JPGSUFFIX;
            } else if (person.getAvatar_iqiyi() != null) {
                avatarName = person.getPersonId() + StringConst.UNDERLINE + 1 + StringConst.JPGSUFFIX;
            } else if (person.getAvatar_youku() != null) {
                avatarName = person.getPersonId() + StringConst.UNDERLINE + 2 + StringConst.JPGSUFFIX;
            } else {
                avatarName = "default.jpg";
            }
            personJson.put("avatar", avatarRoot + avatarName);

            String gender = person.getGender();
            String sex = null;
            if (gender == null) {
                sex = StringConst.EMPTY;
            } else if ("m".equalsIgnoreCase(gender)) {
                sex = "男";
            } else if ("f".equalsIgnoreCase(gender)) {
                sex = "女";
            } else if ("g".equalsIgnoreCase(gender)) {
                sex = "组合";
            }
            personJson.put("gender", sex);

            personJson
                    .put("nationality", person.getNationality() == null ? StringConst.EMPTY : person.getNationality());
            personJson.put("bloodtype", person.getBloodtype() == null ? StringConst.EMPTY : person.getBloodtype());
            personJson.put("constellation",
                    person.getConstellation() == null ? StringConst.EMPTY : person.getConstellation());
            personJson.put("birthday", person.getBirthday() == null ? StringConst.EMPTY : person.getBirthday());
            personJson.put("height", person.getHeight() == null ? StringConst.EMPTY : person.getHeight());
            personJson.put("alias", person.getAlias() == null ? StringConst.EMPTY : person.getAlias());
            personJson.put("homeplace", person.getHomeplace() == null ? StringConst.EMPTY : person.getHomeplace());
            personJson
                    .put("description", person.getDescription() == null ? StringConst.EMPTY : person.getDescription());
            personJson.put("honor", person.getHonor() == null ? StringConst.EMPTY : person.getHonor());

            JSONArray productsArray = new JSONArray();
            List<PersonProduct> products = personManager.getPersonProductsByPersonId(dsKey, personId);
            for (PersonProduct product : products) {
                JSONObject productJson = new JSONObject();
                productJson.put("name", product.getName());
                productJson.put("year", product.getYear());
                productJson.put("category", product.getCategory());
                productJson.put("description", product.getDescription());

                Map<String, String> onlineInfos = product.getOnlineInfos();
                JSONArray onlineArray = new JSONArray();
                if (onlineInfos != null && onlineInfos.size() > 0) {
                    for (String key : onlineInfos.keySet()) {

                        JSONObject onlineInfo = new JSONObject();
                        onlineInfo.put(StringConst.CODE, key);
                        onlineInfo.put(StringConst.NAME, onlineInfos.get(key));

                        onlineArray.put(onlineInfo);
                    }
                }
                productJson.put("onlineInfos", onlineArray.toString());
                productsArray.put(productJson);
            }

            personJson.put("products", productsArray.toString());

        } catch (JSONException e) {
            log.error("Conver person to json object failed, due to exception ");
            e.printStackTrace();
        }

        JSONArray results = new JSONArray();
        results.put(personJson);

        return results.toString();
    }

    public PersonManager getPersonManager() {
        return personManager;
    }

    public void setPersonManager(PersonManager personManager) {
        this.personManager = personManager;
    }

    public SystemCache getSystemCache() {
        return systemCache;
    }

    public void setSystemCache(SystemCache systemCache) {
        this.systemCache = systemCache;
    }
}